package cn.personal.library.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import cn.personal.library.R;

/**
 * viewpager 指示器
 *
 * @author zengdexing
 */
public class ViewPagerIntroduction extends LinearLayout {
    private Drawable normalBG;
    private Drawable selectBG;
    private int contentMargin = 15;

    public ViewPagerIntroduction(Context context) {
        this(context, null);
    }

    public ViewPagerIntroduction(Context context, AttributeSet attrs) {
        super(context, attrs);
        setGravity(Gravity.CENTER);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIntroduction);
        contentMargin = typedArray.getDimensionPixelSize(R.styleable.ViewPagerIntroduction_introduction_margin, 15);
        normalBG = typedArray.getDrawable(R.styleable.ViewPagerIntroduction_introduction_normal);
        if(normalBG == null)
            normalBG = getResources().getDrawable(R.drawable.viewpager_introduction_normal);

        selectBG = typedArray.getDrawable(R.styleable.ViewPagerIntroduction_introduction_checked);
        if(selectBG == null)
            selectBG = getResources().getDrawable(R.drawable.viewpager_introduction_checked);

        int size = typedArray.getInt(R.styleable.ViewPagerIntroduction_introduction_count, 0);
        setSize(size);

        typedArray.recycle();
    }

    /**
     * 设置指示器数量
     *
     * @param size
     */
    public void setSize(int size) {
        removeAllViews();
        for (int i = 0; i < size; i++) {
            ImageView imageView = new ImageView(getContext());
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            imageView.setScaleType(ScaleType.CENTER);
            if(i == 0) {
                imageView.setImageDrawable(selectBG);
            } else {
                params.leftMargin = contentMargin;
                imageView.setImageDrawable(normalBG);
            }
            addView(imageView, params);
        }
    }

    public void select(int select) {
        if(select < getChildCount()) {
            for (int i = 0; i < getChildCount(); i++) {
                if(i == select) {
                    ImageView current = ((ImageView) (getChildAt(select)));
                    if(current != null) {
                        current.setImageDrawable(selectBG);
                    }
                } else {
                    ImageView pre = ((ImageView) (getChildAt(i)));
                    if(pre != null) {
                        pre.setImageDrawable(normalBG);
                    }
                }
            }
        }
    }
}
